package com.ls.modules.sys.biz.manager;

import com.ls.base.utils.R;
import com.ls.common.baseClass.BackStageService;
import com.ls.common.oauth.TokenGenerator;
import com.ls.modules.sys.dal.jpa.dao.SysUserTokenDao;
import com.ls.modules.sys.dal.jpa.entity.SysUserTokenEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Optional;

/**
 * @author: xiaosu
 * @date: 2018-09-25  17:20
 */
@Service("sysUserTokenManager")
public class SysUserTokenManager extends BackStageService {

    @Autowired
    private SysUserTokenDao  sysUserTokenDao;

    /**
     * 1小时后过期（单位秒），类似于session 的过期时间
     */
    private final static int EXPIRE = 3600;

    /**
     * 用户登录 生成token
     * @param userId
     * @return
     */
    public R createToken(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //当前时间
        Date now = new Date();
        //过期时间
        Date expireTime = new Date(now.getTime() + EXPIRE * 1000);



        //判断是否生成过token
        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        Optional<SysUserTokenEntity> optional=  sysUserTokenDao.findById(userId);
        if(!optional.isPresent()){
            tokenEntity.setUserId(userId);
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //保存token
            sysUserTokenDao.save(tokenEntity);
        }else{
            tokenEntity=optional.get();
            tokenEntity.setToken(token);
            tokenEntity.setUpdateTime(now);
            tokenEntity.setExpireTime(expireTime);

            //更新token
            sysUserTokenDao.save(tokenEntity);
        }

        R r = R.ok().put("token", token).put("expire", EXPIRE);

        return r;
    }


    /**
     * 用户 退出登录时 生成新的token
     * @param userId
     */
    public void logout(long userId) {
        //生成一个token
        String token = TokenGenerator.generateValue();

        //修改token
        SysUserTokenEntity tokenEntity = new SysUserTokenEntity();
        tokenEntity.setUserId(userId);
        tokenEntity.setToken(token);
        sysUserTokenDao.save(tokenEntity);
    }


}
